package cn.itcast.bos.web.action.take_delivery;

import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.pagehelper.PageResult;
import cn.itcast.bos.service.take_delivery.PromotionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

/**
 * 宣传活动 管理
 *
 * @author ChuanJing
 * @date 2018/6/4 14:36
 */
@Controller
public class PromotionController {

    @Autowired
    private PromotionService promotionService;

    @RequestMapping("/promotion_pageQuery")
    @ResponseBody
    public PageResult pageQuery(int page, int rows) {
        // 构造分页查询参数
        Pageable pageable = new PageRequest(page-1, rows);

        // 调用业务层 完成查询
        Page<Promotion> pageData = promotionService.findPageData(pageable);

        PageResult pageResult = new PageResult(pageData.getTotalElements(), pageData.getContent());

        return pageResult;
    }

    @RequestMapping(value="/promotion_save",method= RequestMethod.POST)
    public String updateItem(MultipartFile titleImgFile, Promotion promotion, HttpServletRequest request) throws Exception {
        // 宣传图 上传、在数据表保存 宣传图路径
        // 绝对路径
        String savePath = request.getSession().getServletContext().getRealPath("/upload/titleImg/");
        System.out.println("绝对路径：" + savePath);//最后没有“/”
        // 相对路径
        String saveUrl = request.getContextPath() + "/upload/titleImg/";
        System.out.println("相对路径：" + saveUrl);//最后有“/”

        // 生成随机图片名
        UUID uuid = UUID.randomUUID();
        //String ext = titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
        //取文件扩展名
        String oriName = titleImgFile.getOriginalFilename();
        String extName = oriName.substring(oriName.lastIndexOf("."));
        String randomFileName = uuid + extName;

        // 保存图片 (绝对路径)
        File destFile = new File(savePath + "/" + randomFileName);
        // System.out.println("保存图片 (绝对路径)：" + destFile.getAbsolutePath());
        titleImgFile.transferTo(destFile);


        // 将保存路径 相对工程web访问路径，保存model中
        promotion.setTitleImg(saveUrl + randomFileName);

        // 调用业务层，完成活动任务数据保存
        promotionService.save(promotion);

        return "redirect:/pages/take_delivery/promotion.html";
    }
}
